package yiran.onemonthcard.command;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import yiran.onemonthcard.OneMonthCard;
import yiran.onemonthcard.system.OneMonthCardSystem;
import yiran.onemonthcard.lang.LangHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OneMonthCardCommand implements CommandExecutor, TabCompleter {
    private final OneMonthCardSystem OneMonthCardSystem;
    private final OneMonthCard plugin;

    public OneMonthCardCommand(OneMonthCardSystem OneMonthCardSystem, OneMonthCard plugin) {
        this.OneMonthCardSystem = OneMonthCardSystem;
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (args.length == 0) {
            if (!(sender instanceof Player)) {
                sender.sendMessage(LangHelper.getString("errors.command_player_only"));
                return true;
            }
            showOneMonthCardStatus((Player)sender, sender);
            return true;
        }

        switch (args[0].toLowerCase()) {
            case "buy":
                handleBuyCommand(sender, args);
                break;
            case "claim":
                if (!(sender instanceof Player)) {
                    sender.sendMessage(LangHelper.getString("errors.command_player_only"));
                    return true;
                }
                OneMonthCardSystem.giveDailyReward((Player)sender);
                break;
            case "check":
                handleCheckCommand(sender, args);
                break;
            case "reload":
                if (!sender.isOp()) {
                    sender.sendMessage(LangHelper.getString("errors.no_permission"));
                    return true;
                }
                plugin.reloadConfig();
                LangHelper.reload();
                sender.sendMessage(LangHelper.getString("messages.config_reloaded"));
                break;
            case "help":
                sendHelp(sender);
                break;
            default:
                sender.sendMessage(LangHelper.getString("errors.unknown_command"));
                sendHelp(sender);
        }
        return true;
    }

    private void sendHelp(CommandSender sender) {
        sender.sendMessage(LangHelper.getString("commands.help_title"));

        for (String helpLine : LangHelper.getStringList("commands.help_list")) {
            sender.sendMessage(helpLine);
        }
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
        if (args.length == 1) {
            // 第一个参数：显示所有子命令
            List<String> completions = new ArrayList<>();
            completions.add("help");
            completions.add("buy");
            completions.add("claim");
            completions.add("check");
            completions.add("reload");

            // 过滤匹配当前输入的命令
            return filterCompletions(completions, args[0]);
        } else if (args.length == 2) {
            // 第二个参数：根据第一个命令提供补全
            switch (args[0].toLowerCase()) {
                case "buy":
                case "check":
                    // 提供在线玩家列表
                    return getOnlinePlayerNames(sender, args[1]);
                default:
                    return Collections.emptyList();
            }
        }
        return Collections.emptyList();
    }

    private List<String> filterCompletions(List<String> completions, String input) {
        List<String> result = new ArrayList<>();
        if (input == null || input.isEmpty()) {
            return completions;
        }

        String lowerInput = input.toLowerCase();
        for (String completion : completions) {
            if (completion.toLowerCase().startsWith(lowerInput)) {
                result.add(completion);
            }
        }
        return result;
    }

    // 获取玩家名称列表
    private List<String> getOnlinePlayerNames(CommandSender sender, String input) {
        List<String> playerNames = new ArrayList<>();

        // 添加在线玩家
        for (Player player : Bukkit.getOnlinePlayers()) {
            playerNames.add(player.getName());
        }

        // 如果是管理员，添加所有已知玩家（从数据库）
        if (sender.hasPermission("OneMonthCard.admin")) {
            // 获取所有在数据库中有记录的玩家
            List<String> knownPlayers = OneMonthCardSystem.databaseManager.getAllPlayerNames();
            for (String playerName : knownPlayers) {
                if (!playerNames.contains(playerName)) {
                    playerNames.add(playerName);
                }
            }
        }

        return filterCompletions(playerNames, input);
    }

    private void handleCheckCommand(CommandSender sender, String[] args) {
        if (!(sender instanceof Player) && args.length < 2) {
            sender.sendMessage(LangHelper.getString("errors.command_player_only_or_specify_player"));
            return;
        }

        Player target;
        if (args.length >= 2) {
            // 检查是否有权限查询他人
            if (!sender.hasPermission("OneMonthCard.admin")) {
                sender.sendMessage(LangHelper.getString("errors.no_permission"));
                return;
            }

            target = Bukkit.getPlayer(args[1]);
            if (target == null) {
                sender.sendMessage(LangHelper.getString("errors.player_not_found", args[1]));
                return;
            }
        } else {
            // 查询自己
            target = (Player) sender;
        }

        showOneMonthCardStatus(target, sender);
    }

    private void handleBuyCommand(CommandSender sender, String[] args) {
        if (!sender.isOp()) {
            sender.sendMessage(LangHelper.getString("errors.no_permission"));
            return;
        }

        Player target;
        if (args.length >= 2) {
            // 为指定玩家购买
            target = Bukkit.getPlayer(args[1]);
            if (target == null) {
                sender.sendMessage(LangHelper.getString("errors.player_not_found", args[1]));
                return;
            }
            if (!OneMonthCardSystem.getPlayerDataMap().containsKey(target.getName())) {
                OneMonthCardSystem.OneMonthCardData data = OneMonthCardSystem.databaseManager.loadOneMonthCardData(target.getName());
                if (data != null) {
                    OneMonthCardSystem.getPlayerDataMap().put(target.getName(), data);
                }
            }
        } else {
            // 为自己购买
            if (!(sender instanceof Player)) {
                sender.sendMessage(LangHelper.getString("errors.command_player_only"));
                return;
            }
            target = (Player)sender;
        }

        OneMonthCardSystem.purchaseOneMonthCard(target);
        sender.sendMessage(LangHelper.getString("messages.purchase_for_other_success", target.getName()));
    }

    private void showOneMonthCardStatus(Player target, CommandSender sender) {
        OneMonthCardSystem.OneMonthCardData data = OneMonthCardSystem.getPlayerDataMap().get(target.getName());
        if (data != null && data.isActive()) {
            sender.sendMessage(LangHelper.getString(
                    "messages.status_active_player",
                    target.getName(),
                    data.getRemainingDays()
            ));
        } else {
            sender.sendMessage(LangHelper.getString(
                    "errors.status_inactive_player",
                    target.getName()
            ));
        }
    }
}
